package com.guoxin.concurrentprogramming.chapter3.threadpool;

import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

/**
 * fork join 框架的使用
 *
 * @author guoxin
 * @date 2019/7/16
 */
public class CountTask extends RecursiveTask<Long> {

    private long start, end;
    private static final int THRESHOLD = 10000;

    private CountTask(long start, long end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Long compute() {
        long sum = 0;
        boolean canCompute = (end - start) < THRESHOLD;
        if (canCompute) {
            for (long i = start; i < end; i++) {
                sum += i;
            }
        } else {
            //分成100个小任务
            long step = (start + end) / 100;
            ArrayList<CountTask> subTasks = new ArrayList<>();
            long pos = start;
            for (int i = 0; i < 100; i++) {
                long lastOne = pos + step;
                if (lastOne > end) {
                    lastOne = end;
                }
                CountTask task = new CountTask(pos, lastOne);
                pos += step + 1;
                subTasks.add(task);
                task.fork();
            }

            for (CountTask t : subTasks) {
                sum += t.join();
            }

        }
        return sum;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        ForkJoinTask<Long> result = forkJoinPool.submit(new CountTask(0, 200000L));
        System.out.println(result.get());
    }
}
